﻿
//Queue这种队列是线程不安全的
Queue<int> queue = new Queue<int>();
object obj = new object();

//定义生产者
Thread producer = new Thread(ProducerFunc);


//定义两个消费者
Thread consumer1 = new Thread(ConsumerFunc);
Thread consumer2 = new Thread(ConsumerFunc);

producer.Start();

//等待生产者全部生产完成了，才开始消费者的任务
producer.Join();

consumer1.Start();
consumer2.Start();

//睡眠500毫米，腾出这个时间让消费者完成所有的消费任务
//因为消费函数中使用了while(true)
Thread.Sleep(100);

//强行终止两个消费者的任务，否则while(true),一直死循环
consumer1.Interrupt();
consumer2.Interrupt();

consumer1.Join();
consumer2.Join();

Console.ReadLine();



void ProducerFunc()
{
    for (int i = 1; i <= 20; i++)
    {
        //入队
        queue.Enqueue(i);
    }
}

void ConsumerFunc()
{
    try
    {
        while (true)
        {
            lock (obj)
            {
                if (queue.TryDequeue(out var res))
                {
                    Console.WriteLine($"当前出队:{res}");
                }
            }
        }
    }
    catch (ThreadInterruptedException)
    {
        Console.WriteLine("Thread interrupted");
    }
}